<?php

class ArticleService extends BaseService
{
    private static $self = NULL;

    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }

        return self::$self;
    }


    private $mArticle               = NULL;


    public function __construct()
    {
        $this->mArticle              = new Involved_ArticleModel();

    }


    /**
     * 表单参数
     * @param $obj
     * @param $arr
     * @author  alice
     * @date    2016-1-14
     * @return bool
     */
    public function  checkProperties($obj, $arr)
    {
        if(empty($arr)) return true;
        $obj    =   (array) $obj;

        foreach($arr as $v){
            if(empty($obj[$v])){
                return false;}
        }
        return true;
    }

    /**
     * 文章列表
     * @author alice
     * @date 2016-1-22
     * @return mixed
     */
    public function ShowArticleList()
    {
        return $this->mArticle->ShowArticleList();
    }

    /**
     * 添加文章
     * @param $paramObj
     * @author alice
     * @date 2016-1-22
     * @return int
     * @throws Exception
     */
    public function AddArticle($paramObj)
    {
        #参数验证
        $check = $this->checkProperties($paramObj, ['article_title']);
        if (!$check) {
            throw new Exception($this->error_msg[ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST],
                ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #上传图片处理
        if(!empty($paramObj->img))
        {
            $file = $paramObj->img;
            $clientName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $newName = md5(date('ymdhis') . $clientName) . "." . $extension;
            $file->move(public_path() . '/resource/upload', $newName);

            #生成缩略图
            ThumbnailService::instance()->setImageSize(375, 275);
            $image = file_get_contents(public_path() . '/resource/upload/' . $newName);
            ThumbnailService::instance()->loadData($image, 'image/jpeg');
            ThumbnailService::instance()->buildThumb(public_path() . '/resource/upload/thumb_' . $newName);

            $aData['img'] = '/resource/upload/' . $newName;
        }

        #添加文章
        $aData = [
            'article_title'         => $paramObj->article_title,
            'author'                => $paramObj->author,
            'keywords'              => $paramObj->keywords,
            'cate_id'               => $paramObj->cate_id,
            'brief'                 => $paramObj->brief,
            'content'               => $paramObj->content,
        ];

        return $this->mArticle->insert($aData);




    }
}